﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using GCELibrary.Current;
using System.IO;

namespace ZF.BLL
{
  

    public class DictionaryConfig
    {
        #region HBaseFacility 基础设施
        private static List<Keyword<int>> _HBaseFacility = null;
        /// <summary>
        /// 基础设施
        /// </summary>
        public static List<Keyword<int>> HBaseFacility
        {
            get {
                if (_HBaseFacility == null)
                {
                    _HBaseFacility = GetKeywordList<int>("HBaseFacility");
                }
                return _HBaseFacility;
            }
        }
    
        #endregion

        #region HDecoration 装修
        private static List<Keyword<string>> _HDecoration = null;
        /// <summary>
        /// 装修
        /// </summary>
        public static List<Keyword<string>> HDecoration
        {
            get
            {
                if (_HDecoration == null)
                {
                    _HDecoration = GetDictionary("HDecoration");
                }
                return _HDecoration;
            }
        }
      
        #endregion

        #region HProperty 产权
        private static List<Keyword<string>> _HProperty = null;
        /// <summary>
        /// 产权
        /// </summary>
        public static List<Keyword<string>> HProperty
        {
            get
            {
                if (_HProperty == null)
                {
                    _HProperty = GetDictionary("HProperty");
                }
                return _HProperty;
            }
        }

        #endregion

        #region HWithFacility 配套设施
        private static List<Keyword<int>> _HWithFacility = null;
        /// <summary>
        /// 配套设施
        /// </summary>
        public static List<Keyword<int>> HWithFacility
        {
            get
            {
                if (_HWithFacility == null)
                {
                    _HWithFacility = GetKeywordList<int>("HWithFacility");
                }
                return _HWithFacility;
            }
        }

        #endregion

        #region HPeriphery 周边配套
        private static List<Keyword<int>> _HPeriphery = null;
        /// <summary>
        /// 周边配套
        /// </summary>
        public static List<Keyword<int>> HPeriphery
        {
            get
            {
                if (_HPeriphery == null)
                {
                    _HPeriphery = GetKeywordList<int>("HPeriphery");
                }
                return _HPeriphery;
            }
        }

        #endregion



        #region HDirection 朝向
        private static List<Keyword<string>> _HDirection = null;
        /// <summary>
        /// 朝向
        /// </summary>
        public static List<Keyword<string>> HDirection
        {
            get
            {
                if (_HDirection == null)
                {
                    _HDirection = GetDictionary("HDirection");
                }
                return _HDirection;
            }
        }

        #endregion

        #region HHouseType 物业类型
        private static List<Keyword<string>> _HHouseType = null;
        /// <summary>
        /// 物业类型
        /// </summary>
        public static List<Keyword<string>> HHouseType
        {
            get
            {
                if (_HHouseType == null)
                {
                    _HHouseType = GetDictionary("HHouseType");
                }
                return _HHouseType;
            }
        }

      

        #endregion

        #region HAreaTree 地区树
        private static List<SimpleTree<int>> _HAreaTree = null;
        /// <summary>
        /// 地区树 
        /// </summary>
        public static List<SimpleTree<int>> HAreaTree
        {
            get
            {
                if (_HAreaTree == null)
                {
                    using (var dc = SiteInfo.CreateDBDataContext())
                    {
                        var list = dc.Dic_Area.ToList();
                        var areaList = list.Select(p => new SimpleTree<int>()
                        {
                            Id = p.AreaId,
                            Name = p.Name,
                            ParentId = p.ParentId,
                        }).ToList();
                        areaList.ForEach(p =>
                        {
                            if (p.ParentId != 0)
                            {
                                var parent = areaList.FirstOrDefault(a => a.Id == p.ParentId);
                                if (parent != null)
                                {
                                    parent.Childs.Add(p);
                                }
                            }
                          
                        });
                        areaList = areaList.Where(p => p.ParentId == 0).ToList();
                        _HAreaTree = areaList;
                    }
                }
                return _HAreaTree;
            }
        }

        #endregion

        #region HArea 地区
        private static List<Model.Dic_Area> _HArea = null;
        /// <summary>
        /// 地区 
        /// </summary>
        public static List<Model.Dic_Area> HArea
        {
            get
            {
                if (_HArea == null)
                {
                    using (var dc = SiteInfo.CreateDBDataContext())
                    {
                        var list = dc.Dic_Area.ToList();
                        _HArea = list;
                    }
                }
                return _HArea;
            }
        }



        #endregion

        #region INewType 新闻类别
        private static List<Keyword<string>> _INewType = null;
        /// <summary>
        /// 新闻类别
        /// </summary>
        public static List<Keyword<string>> INewType
        {
            get
            {
                if (_INewType == null)
                {
                    _INewType = GetDictionary("INewType");
                }
                return _INewType;
            }
        }



        #endregion

        #region IInfoType 分类类别
        private static List<Model.Dic_InforType> _IInfoType = null;
        /// <summary>
        /// 分类类别
        /// </summary>
        public static List<Model.Dic_InforType> IInfoType
        {
            get
            {
                if (_IInfoType == null)
                {
                    using (var dc = SiteInfo.CreateDBDataContext())
                    {
                        var list = dc.Dic_InforType.OrderByDescending(p=>p.OrderId).ToList();
                        _IInfoType = list;
                    }
           
                }
                return _IInfoType;
            }
        }



        #endregion

        #region GOfferingType 供品类型
        private static List<Keyword<string>> _GOfferingType = null;
        /// <summary>
        /// 供品类型
        /// </summary>
        public static List<Keyword<string>> GOfferingType
        {
            get
            {
                if (_GOfferingType == null)
                {
                    using (var dc = SiteInfo.CreateDBDataContext())
                    {

                        _GOfferingType = GetDictionary("GOfferingType");
                    }

                }
                return _GOfferingType;
            }
        }



        #endregion

        #region APopularizeCompanyType 推广商家类型
        private static List<Keyword<int>> _APopularizeCompanyType = null;
        /// <summary>
        /// 推广商家类型
        /// </summary>
        public static List<Keyword<int>> APopularizeCompanyType
        {
            get
            {
                if (_APopularizeCompanyType == null)
                {
                    _APopularizeCompanyType = GetKeywordList<int>("APopularizeCompanyType");
                }
                return _APopularizeCompanyType;
            }
        }

        #endregion

 
        public static List<MTypeJson> MTypeJsonList
        {
            get
            {
                string cacheKey="DictionaryConfig_MTypeJsonList";
                var cache= HttpCache.GetCache(cacheKey);
                if (cache != null && cache is List<MTypeJson>)
                {
                    return cache as List<MTypeJson>;
                }
                else
                {
                    using (var dc = SiteInfo.CreateDBDataContext())
                    {
                        var list = dc.Dic_MerchandiseType.Where(p=>!p.IsDel).ToList();
                        var jsonList = list.Select(p =>
                            new MTypeJson()
                            {
                                Params = string.IsNullOrEmpty(p.Param) ? null : Newtonsoft.Json.JsonConvert.DeserializeObject<Model.MTypeJsonModel[]>(p.Param),
                                MType = p,
                            }).ToList();
                        SiteInfo.Instance.SetPageCache(cacheKey, jsonList);
                        //HttpCache.SetCache(cacheKey, jsonList, SiteInfo.Instance.SystemConfig.DefCacheTimeSpan);
                        return jsonList;
                    }
                }
              
            }
        }


        #region EExpertType 在线专家类型
        private static List<Keyword<int>> _EExpertType = null;
        /// <summary>
        /// 在线专家类型
        /// </summary>
        public static List<Keyword<int>> EExpertType
        {
            get
            {
                if (_EExpertType == null)
                {
                    _EExpertType = GetKeywordList<int>("EExpertType");
                }
                return _EExpertType;
            }
        }

        #endregion



        private static List<Keyword<T>> GetKeywordList<T>(string key)
        {
            var xeConfig = GetConfig();
            var xeItem = XmlHelper.GetFirstXmlElement(xeConfig, string.Format("dictionary[@key='{0}']", key));
            var result = new List<Keyword<T>>();
            if (xeItem != null)
            {
                foreach (XmlNode xn in xeItem.ChildNodes)
                {
                    var xnKey = xn.Attributes["key"];
                    var xnText = xn.Attributes["text"];
                    if (xnKey != null && xnText != null)
                    {
                        result.Add(new Keyword<T>
                        {
                            Key = xnKey.Value.Convert<T>(),
                            Text = xnText.Value,
                        });
                    }
                    else
                    {
                        throw new ApplicationException(string.Format("系统异常!字典{0}节点配置错误", key));
                    }
                }
            }
            else
                throw new ApplicationException(string.Format("系统异常!字典{0}节点配置错误", key));
            return result;
        }
        private static List<Keyword<string>> GetDictionary(string key)
        {
            var xeConfig = GetConfig();
            var xeItem = XmlHelper.GetFirstXmlElement(xeConfig, string.Format("dictionary[@key='{0}']", key));
            var result = new List<Keyword<string>>();
            if (xeItem != null)
            {
                foreach (XmlNode xn in xeItem.ChildNodes)
                {
                    var xnText = xn.Attributes["text"];
                    if (xnText != null)
                    {
                        result.Add(new Keyword<string>
                        {
                            Key = xnText.Value,
                            Text = xnText.Value,
                        });
                    }
                    else
                    {
                        throw new ApplicationException(string.Format("系统异常!字典{0}节点配置错误", key));
                    }
                }
            }
            else
                throw new ApplicationException(string.Format("系统异常!字典{0}节点配置错误", key));
            return result;
        }

        private static XmlElement GetConfig()
        {
           
            if (!File.Exists(ConfigFilePath))
                throw new FileNotFoundException("系统异常!未找到匹配文件");
            var xDoc = new XmlDocument();
            xDoc.Load(ConfigFilePath);
            return XmlHelper.GetFirstXmlElement(xDoc, "dictionarys");
 
        }
        private static string ConfigFilePath
        {
            get
            {
                //return AppDomain.CurrentDomain.BaseDirectory + @"BaseInfo.xml";
                return AppDomain.CurrentDomain.BaseDirectory + @"\bin\BaseInfo.xml";

            }
        }

        private static Dictionary<string, DateTime> dicCahceTime = new Dictionary<string, DateTime>(); 
        private static bool CheckCacheTimeOut(string key)
        {
            if (dicCahceTime.ContainsKey(key))
            {
                return dicCahceTime[key].AddMinutes(30) > DateTime.Now;
            }
            return false;

        }
    }

 
     

    public class Keyword<T>
    {
        public T Key { get; set; }
        public string Text { get; set; }
    }

    public class SimpleTree<T>
    {
        public SimpleTree()
        {
            Childs = new List<SimpleTree<T>>();
        }
        public T Id { get; set; }
        public string Name { get; set; }
        public List<SimpleTree<T>> Childs { get; set; }
        public T ParentId { get; set; }
     
    }

    public class MTypeJson
    {
        public Model.Dic_MerchandiseType MType { get; set; }
        public Model.MTypeJsonModel[] Params { get; set; }
    }

}
